
package com.huizhan.web.controller;
 
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
import io.swagger.annotations.*;

import java.util.*;
import javax.servlet.http.HttpServletRequest;

import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.view.*;

/**
 * 赠票api
 */
 
@Api(tags = "TicketComplimentary",description = "赠票")
@RestController
public class TicketComplimentaryController {
    
    @Autowired
    private TicketComplimentaryDao dao;
   
    @Autowired
    private TicketTypeDao daoType;
   
    @Autowired
    private TicketDao ticketDao;
    
    @Autowired
    private TicketRecordDao recordDao;
    
    @Autowired
    private ProjectDao projectDao;
    /**
     * 获取赠票集合
     * @return api结果
     */
    @ApiOperation(value = "获取赠票集合")
    @RequestMapping(value =  "/api/TicketComplimentary/",method = {RequestMethod.GET})
    public ApiResult<List<TicketComplimentary>> Get(){
         ApiResult<List<TicketComplimentary>> result=new ApiResult<List<TicketComplimentary>>();
        try 
        {
            List<TicketComplimentary> res = dao.findAll();
            result.setData(res);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据ID获取赠票信息
     * @param id 赠票ID
     * @return api结果
     */
    @ApiOperation(value = "根据ID获取赠票信息")
    @RequestMapping(value =  "/api/TicketComplimentary/{id}",method = {RequestMethod.GET})
    public ApiResult<TicketComplimentary> Get(@PathVariable Long id){
        ApiResult<TicketComplimentary> result=new ApiResult<TicketComplimentary>();
        try
        {
            TicketComplimentary model= dao.getOne(id);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 查询赠票集合
     * @param model 账号信息
     * @return api结果
     */
    @ApiOperation(value = "查询赠票集合")
    @RequestMapping(value =  "/api/TicketComplimentary/Search",method = {RequestMethod.POST})
    public ApiResult<List<TicketComplimentary>> Search(@RequestBody PageTicketComplimentary model){
         ApiResult<List<TicketComplimentary>> result=new ApiResult<List<TicketComplimentary>>();
         
        try
        {    
            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"ticket_complimentary_Id") ;            
            Page<TicketComplimentary> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getLevel(),pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        
        return result;
    }

    /**
     * 修改赠票信息
     * @param id 赠票ID
     * @param model 赠票信息
     * @return api结果
     */
    @ApiOperation(value = "赠票")
    @RequestMapping(value =  "/api/TicketComplimentary/{id}",method = {RequestMethod.PUT})
    public ApiResult<TicketComplimentary> Edit(@PathVariable Long id,@RequestBody TicketComplimentary model,HttpServletRequest request){
        ApiResult<TicketComplimentary> result=new ApiResult<TicketComplimentary>();
        try
        {
            Optional<TicketComplimentary> ticket=dao.findById(id);
            Long count=model.getTotal();

            if(ticket.isPresent()){
                if(ticket.get().getUseNumber()==null){
                    ticket.get().setUseNumber(0L);
                }
                if(ticket.get().getTotal()-ticket.get().getUseNumber()<count){
                    result.setHasError(true);
                    result.setMessage("赠票数量不能大于:"+(ticket.get().getTotal()-ticket.get().getUseNumber()));
                }else{
                    ticket.get().setUseNumber(ticket.get().getUseNumber()+count);

                    dao.save(ticket.get());

                    TicketComplimentary complimentary=dao.findByProjectIdAndPhoneAndTicketTypeId(ticket.get().getProjectId(), model.getPhone(),ticket.get().getTicketTypeId());

                    TicketRecord record=new TicketRecord();

                    if(complimentary==null){
                        model.setLevel(ticket.get().getLevel()==null?1:ticket.get().getLevel()+1);
                        model.setParentId(ticket.get().getTicketComplimentaryId());
                        model.setTicketTypeId(ticket.get().getTicketTypeId());
                        model.setCreateDate(new Date());
                        model.setProjectId(ticket.get().getProjectId());
                        model.setTypeName(ticket.get().getTypeName());
                        model.setUseNumber(0L);
                        dao.save(model);
                        record.setTicketComplimentaryId(model.getTicketComplimentaryId());
                        complimentary=model;
                    }else{
                        complimentary.setTotal(complimentary.getTotal()+count);
                        dao.save(complimentary);
                        record.setTicketComplimentaryId(complimentary.getTicketComplimentaryId());
                    }

                    int size=Integer.valueOf(model.getTotal().toString());

                    PageRequest pageable = PageRequest.of(0,size ,Direction.ASC,"is_Passage") ;   

                    Page<Ticket> list=ticketDao.findByWhere(id, pageable);

                    for (Ticket ticket2 : list.getContent()) {
                        ticket2.setTicketComplimentaryId(complimentary.getTicketComplimentaryId());
                        ticket2.setName(model.getPhone());
                    }

                    ticketDao.saveAll(list.getContent());

                    record.setProjectId(ticket.get().getProjectId());
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setCreateDate(new Date());
                    record.setLevel(ticket.get().getLevel()==null?1:ticket.get().getLevel()+1);
                    record.setNumber(model.getTotal());
                    record.setParentId(id);
                    record.setTicketTypeId(ticket.get().getTicketTypeId());
                    record.setTypeName(ticket.get().getTypeName());
                    record.setType(1L);
                    record.setRemark(model.getPhone()+"("+model.getName()+")收到"+ticket.get().getPhone()+"("+ticket.get().getName()+")"+"赠票"+model.getTotal()+"张");
                    recordDao.save(record);

                    record=new TicketRecord();
                    record.setTypeName(ticket.get().getTypeName());
                    record.setCreateDate(new Date());
                    record.setProjectId(ticket.get().getProjectId());
                    record.setLevel(ticket.get().getLevel()==null?1:ticket.get().getLevel()+1);
                    record.setTicketTypeId(ticket.get().getTicketTypeId());
                    record.setType(1L);
                    record.setRemark("从"+ticket.get().getPhone()+"("+ticket.get().getName()+")"+"赠给"+model.getPhone()+"("+model.getName()+")"+model.getTotal()+"张票");
                    record.setTicketRecordId(null);
                    record.setTicketComplimentaryId(id);
                    record.setParentId(null);
                    record.setPhone(ticket.get().getPhone());
                    record.setName(ticket.get().getName());
                    record.setNumber(-model.getTotal());                    
                    recordDao.save(record);
                    
                    Project project=projectDao.getOne(ticket.get().getProjectId());

                    SendSMS(project,complimentary,count,list.getContent(),request);
                }
            }else{
                result.setHasError(true);
                result.setMessage("参数错误");
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    private Boolean SendSMS(Project project,TicketComplimentary model,Long count,List<Ticket> list,HttpServletRequest request){

        boolean b=false;

        try {
            String data="{\"account\":\"dh81653\",\"password\":\""+
            TenpayUtil.MD5("e3YiG73c").toLowerCase()
            +"\",\"msgid\":\""
            +(UUID.randomUUID().toString())
            +"\",\"phones\":"
            +model.getPhone()
            +",\"content\":\""
            +model.getName()
            +"您收到"
            +project.getName()
            +"电子票"
            +(count)
            +"张 ";

            /*if(model.getTotal()==count&&count<6){
                for (Ticket ticket : list) {
                    data+=request.getScheme() + "://" + request.getServerName()+"/"+ticket.getTicketTypeId()+","+ticket.getCode()+"\\n";
                }
            }else{*/
                data+=request.getScheme() + "://" + request.getServerName()+"/t/"+model.getTicketComplimentaryId();
            //}

            data+="\",\"sign\":\"【"
            +project.getSignName()
            +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

            TenpayHttpClient httpClient = new TenpayHttpClient();  

            httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
            String  resContent = httpClient.getResContent();

            if(resContent.contains("提交成功")){
                b=true;
            }
        } catch (Exception e) {
             b=false;
        }
       return b;
    }


    /**
     * 添加赠票信息
     * @param model 赠票信息
     * @return api结果
     */
    @ApiOperation(value = "更新赠票信息")
    @RequestMapping(value =  "/api/TicketComplimentary/",method = {RequestMethod.PATCH})
    public ApiResult<TicketComplimentary> Edit(@RequestBody TicketComplimentary model,HttpServletRequest request){
         ApiResult<TicketComplimentary> result=new ApiResult<TicketComplimentary>();
        try
        {
            TicketComplimentary ticketComplimentary = dao.findByProjectIdAndPhoneAndTicketTypeId(model.getProjectId(),model.getPhone(),model.getTicketTypeId());

            if(ticketComplimentary==null){
                result.setHasError(true);
                result.setMessage("手机号码不存在");
            }  else if  (model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }  else if(model.getTotal()<=0){
                result.setHasError(true);
                result.setMessage("票必须大于等于0");
            } else{ 
                TicketType type = daoType.getOne(model.getTicketTypeId());
                Project project=projectDao.getOne(model.getProjectId());

                model.setUseNumber(ticketComplimentary.getUseNumber());
                model.setLevel(ticketComplimentary.getLevel());
                model.setCreateDate(new Date());
                model.setTypeName(type.getName());
                model.setTicketComplimentaryId(ticketComplimentary.getTicketComplimentaryId());

                if(model.getTotal()>ticketComplimentary.getTotal()){
                    List<Ticket> tickets= ticketDao.findByTicketTypeId(model.getTicketTypeId());
                    List<Ticket> list=new ArrayList<Ticket>();

                    for(Integer i=0;i<(model.getTotal()-ticketComplimentary.getTotal());i++){
                        Ticket ticket=new Ticket();
                        getCode(ticket, tickets);
                        ticket.setIdNumber(UUID.randomUUID().toString());
                        ticket.setCreateDate(new Date());
                        ticket.setTicketComplimentaryId(model.getTicketComplimentaryId());
                        ticket.setProjectId(model.getProjectId());
                        ticket.setTicketTypeId(model.getTicketTypeId());
                        ticket.setIsPassage(0);
                        ticket.setName(model.getPhone());
                        list.add(ticket);
                        tickets.add(ticket);
                    }

                    ticketDao.saveAll(list);
                    
                    SendSMS(project, model,model.getTotal()-ticketComplimentary.getTotal(),list,request);
                }else if(model.getTotal()<ticketComplimentary.getTotal()){
                    Integer size=Integer.valueOf(String.valueOf(ticketComplimentary.getTotal()-model.getTotal()));
                    PageRequest pageable = PageRequest.of(0,size ,Direction.ASC,"is_Passage") ;   

                    Page<Ticket> list=ticketDao.findByWhere(ticketComplimentary.getTicketComplimentaryId(),pageable);

                    ticketDao.deleteAll(list.getContent());
                }

                TicketRecord record=new TicketRecord();
                record.setTicketComplimentaryId(model.getTicketComplimentaryId());
                record.setTypeName(type.getName());
                record.setCreateDate(new Date());
                record.setProjectId(type.getProjectId());
                record.setLevel(0L);
                record.setTicketTypeId(type.getTicketTypeId());
                record.setType(1L);
                record.setRemark("系统给"+model.getPhone()+"("+model.getName()+")"+(model.getTotal()-ticketComplimentary.getTotal())+"张票");
                record.setPhone(model.getPhone());
                record.setName(model.getName());
                record.setNumber(model.getTotal()-ticketComplimentary.getTotal());                    
                recordDao.save(record);

                dao.save(model);

                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 添加赠票信息
     * @param model 赠票信息
     * @return api结果
     */
    @ApiOperation(value = "添加赠票信息")
    @RequestMapping(value =  "/api/TicketComplimentary/",method = {RequestMethod.POST})
    public ApiResult<TicketComplimentary> Add(@RequestBody TicketComplimentary model,HttpServletRequest request){
         ApiResult<TicketComplimentary> result=new ApiResult<TicketComplimentary>();
        try
        {
            if  (model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            } else if(dao.findByProjectIdAndPhoneAndTicketTypeId(model.getProjectId(),model.getPhone(),model.getTicketTypeId())!=null){
                result.setHasError(true);
                result.setMessage("手机号码已存在");
            }else if(model.getTotal()<1){
                result.setHasError(true);
                result.setMessage("票必须大于0");
            } else{ 
                TicketType type= daoType.getOne(model.getTicketTypeId());
                Project project=projectDao.getOne(model.getProjectId());
                model.setCreateDate(new Date());
                model.setTypeName(type.getName());
                model.setLevel(0L);
                dao.save(model);
                List<Ticket> tickets= ticketDao.findByTicketTypeId(model.getTicketTypeId());
                List<Ticket> list=new ArrayList<Ticket>();

                for(Integer i=0;i<model.getTotal();i++){
                    Ticket ticket=new Ticket();
                    getCode(ticket, tickets);
                    ticket.setIdNumber(UUID.randomUUID().toString());
                    ticket.setCreateDate(new Date());
                    ticket.setTicketComplimentaryId(model.getTicketComplimentaryId());
                    ticket.setProjectId(model.getProjectId());
                    ticket.setTicketTypeId(model.getTicketTypeId());
                    ticket.setIsPassage(0);
                    ticket.setName(model.getPhone());
                    list.add(ticket);
                    tickets.add(ticket);
                }
                ticketDao.saveAll(list);

                TicketRecord record=new TicketRecord();
                record.setTicketComplimentaryId(model.getTicketComplimentaryId());
                record.setTypeName(type.getName());
                record.setCreateDate(new Date());
                record.setProjectId(type.getProjectId());
                record.setLevel(0L);
                record.setTicketTypeId(type.getTicketTypeId());
                record.setType(1L);
                record.setRemark("系统给"+model.getPhone()+"("+model.getName()+")"+model.getTotal()+"张票");
                record.setPhone(model.getPhone());
                record.setName(model.getName());
                record.setNumber(model.getTotal());                    
                recordDao.save(record);
                SendSMS(project, model,model.getTotal(), list, request);
                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    /**
     * 获取码值
     * @param ticket
     */
    private void getCode(Ticket ticket,List<Ticket> list){
        String no=TenpayUtil.random(5);
        for (Ticket ticket2 : list) {
            if(ticket2.getCode().equals(no)){
                getCode(ticket,list);
            }
        }
        ticket.setCode(no);
    }

    /**
     * 删除赠票信息
     * @param id 赠票ID
     * @return api结果
     */
    @ApiOperation(value = "删除赠票信息")
    @RequestMapping(value =  "/api/TicketComplimentary/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  Long id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            ticketDao.deleteByTicketComplimentaryId(id);
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}

